import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, Edit, CheckCircle, Circle, Calendar, Flag, Folder, Tag, Bot, Save, X, Plus, Trash2, Clock, Loader2 } from 'lucide-react'
import { useModernNotification } from '../components/ModernNotification'
import { aiAPI, taskAPI } from '../services/api'
import { getPriorityColor, getPriorityLabel, getCategoryIcon, getCategoryLabel } from '../utils'
import { TimeUtils, getDateStatus } from '../utils/timeUtils'
import { TimeLabel, TaskTag } from '../components/Tags'

export default function TaskDetailPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { showNotification, NotificationComponent } = useModernNotification()
  interface Task {
    id: string
    title: string
    description?: string
    dueDate?: string
    dueTime?: string // 新增：时间字段
    reminderMinutes?: number // 新增：提醒间隔字段
    priority: string
    category: string
    tags: string[]
    completed: boolean
    notes?: string
    subtasks: Array<{
      id: string
      title: string
      completed: boolean
    }>
    createdAt: string
    updatedAt: string
  }

  const [task, setTask] = useState<Task | null>(null)
  const [editingTask, setEditingTask] = useState<Task | null>(null)
  const [isEditing, setIsEditing] = useState(false)
  const [aiSuggestions, setAiSuggestions] = useState<any[]>([])
  const [showAISuggestions, setShowAISuggestions] = useState(false)
  const [isLoadingAI, setIsLoadingAI] = useState(false)
  const [aiActionLoading, setAiActionLoading] = useState<{ [key: string]: boolean }>({})
  const [isSaving, setIsSaving] = useState(false)
  const [newSubtaskTitle, setNewSubtaskTitle] = useState('')
  const [isAddingSubtask, setIsAddingSubtask] = useState(false)
  const [editingSubtaskId, setEditingSubtaskId] = useState<string | null>(null)
  const [editingSubtaskTitle, setEditingSubtaskTitle] = useState('')
  // 自定义日期时间弹窗
  const [dateModalOpen, setDateModalOpen] = useState(false)
  const [dateModalDate, setDateModalDate] = useState('')
  const [dateModalTime, setDateModalTime] = useState('')
  const dateModalResolverRef = useRef<((value: string | null) => void) | null>(null)

  useEffect(() => {
    if (id) {
      loadTask()
    }
  }, [id])

  const loadTask = async () => {
    try {
      const taskData = await taskAPI.getAllTasks()
      const foundTask = taskData.find(t => t.id === id)
      if (foundTask) {
        // 确保必要字段存在，并解析时间字段
        let dueTime = ''
        let dueDate = foundTask.dueDate
        
        // 如果dueDate包含时间信息，则分离日期和时间
        if (foundTask.dueDate && foundTask.dueDate.includes('T')) {
          const dateTime = new Date(foundTask.dueDate)
          if (!isNaN(dateTime.getTime())) {
            // 使用本地时间而不是UTC时间
            const year = dateTime.getFullYear()
            const month = (dateTime.getMonth() + 1).toString().padStart(2, '0')
            const day = dateTime.getDate().toString().padStart(2, '0')
            const hours = dateTime.getHours().toString().padStart(2, '0')
            const minutes = dateTime.getMinutes().toString().padStart(2, '0')
            
            dueDate = `${year}-${month}-${day}` // YYYY-MM-DD (本地日期)
            dueTime = `${hours}:${minutes}` // HH:mm (本地时间)
          }
        }
        
        const taskWithDefaults = {
          ...foundTask,
          dueDate,
          dueTime,
          reminderMinutes: (foundTask as any).reminder_minutes || (foundTask as any).reminderMinutes || 30,
          subtasks: (foundTask as any).subtasks || [],
          tags: (foundTask as any).tags || []
        }
        setTask(taskWithDefaults)
      } else {
        navigate('/')
      }
    } catch (error) {
      console.error('加载任务失败:', error)
      navigate('/')
    }
  }

  if (!task) return null

  // 安全的日期检查函数
  const isValidTaskDate = (dateStr: any): boolean => {
    if (!dateStr) return false
    const date = new Date(dateStr)
    return date instanceof Date && !isNaN(date.getTime())
  }

  const handleToggleComplete = async () => {
    try {
      const result = await taskAPI.toggleTask(task.id)
      if (result.message) {
        setTask(prev => prev ? { ...prev, completed: !prev.completed } : null)
      }
    } catch (error) {
      console.error('更新任务状态失败:', error)
      alert('更新任务状态失败，请重试')
    }
  }

  const handleEdit = () => {
    if (task) {
      setEditingTask({ ...task })
      setIsEditing(true)
    }
  }

  const handleCancelEdit = () => {
    setEditingTask(null)
    setIsEditing(false)
  }

  const handleSaveEdit = async () => {
    if (!editingTask) return
    
    // 验证必填字段
    if (!editingTask.title || editingTask.title.trim() === '') {
      alert('任务标题不能为空')
      return
    }
    
    setIsSaving(true)
    try {
      // 合并日期和时间
      let fullDateTime = editingTask.dueDate
      if (editingTask.dueDate && editingTask.dueTime) {
        // 正确处理时区：创建本地时间对象，然后转换为UTC时间
        const [hours, minutes] = editingTask.dueTime.split(':').map(Number)
        const localDateTime = new Date(editingTask.dueDate)
        localDateTime.setHours(hours, minutes, 0, 0)
        fullDateTime = localDateTime.toISOString()
      }

      const result = await taskAPI.updateTask(editingTask.id, {
        title: editingTask.title,
        description: editingTask.description,
        dueDate: fullDateTime,
        reminderMinutes: editingTask.reminderMinutes || 30,
        priority: editingTask.priority,
        category: editingTask.category,
        tags: editingTask.tags,
        notes: editingTask.notes
      })
      
      if (result.message) {
        setTask(editingTask)
        setIsEditing(false)
        setEditingTask(null)
      }
    } catch (error) {
      console.error('保存任务失败:', error)
      alert('保存任务失败，请重试')
    } finally {
      setIsSaving(false)
    }
  }

  const handleSubtaskToggle = async (subtaskId: string) => {
    try {
      const result = await taskAPI.toggleSubtask(subtaskId)
      if (result.message) {
        // 更新本地状态
        setTask(prev => prev ? {
          ...prev,
          subtasks: prev.subtasks.map(st => 
            st.id === subtaskId ? { ...st, completed: !st.completed } : st
          )
        } : null)
      }
    } catch (error) {
      console.error('更新子任务状态失败:', error)
      alert('更新子任务状态失败，请重试')
    }
  }

  const handleAddSubtask = async () => {
    if (!newSubtaskTitle.trim() || !task) return
    
    try {
      const result = await taskAPI.createSubtask(task.id, newSubtaskTitle.trim())
      if (result.id) {
        // 添加到本地状态
        setTask(prev => prev ? {
          ...prev,
          subtasks: [...prev.subtasks, {
            id: result.id,
            title: result.title,
            completed: result.completed
          }]
        } : null)
        setNewSubtaskTitle('')
        setIsAddingSubtask(false)
      }
    } catch (error) {
      console.error('添加子任务失败:', error)
      alert('添加子任务失败，请重试')
    }
  }

  const handleEditSubtask = async (subtaskId: string, newTitle: string) => {
    if (!newTitle.trim()) return
    
    try {
      const result = await taskAPI.updateSubtask(subtaskId, { title: newTitle.trim() })
      if (result.message) {
        // 更新本地状态
        setTask(prev => prev ? {
          ...prev,
          subtasks: prev.subtasks.map(st => 
            st.id === subtaskId ? { ...st, title: newTitle.trim() } : st
          )
        } : null)
        setEditingSubtaskId(null)
        setEditingSubtaskTitle('')
      }
    } catch (error) {
      console.error('编辑子任务失败:', error)
      alert('编辑子任务失败，请重试')
    }
  }

  const handleDeleteSubtask = async (subtaskId: string) => {
    if (!confirm('确定要删除这个子任务吗？')) return
    
    try {
      const result = await taskAPI.deleteSubtask(subtaskId)
      if (result.message) {
        // 从本地状态中移除
        setTask(prev => prev ? {
          ...prev,
          subtasks: prev.subtasks.filter(st => st.id !== subtaskId)
        } : null)
      }
    } catch (error) {
      console.error('删除子任务失败:', error)
      alert('删除子任务失败，请重试')
    }
  }

  // 处理AI建议的具体动作 - 使用AI智能参数解析
  const handleSuggestionAction = async (suggestion: any, action: string) => {
    try {
      console.log('执行建议动作:', action, suggestion)
      
      // 使用AI智能解析动作参数
      const parseResult = await aiAPI.parseActionParameters(suggestion, action, task)
      
      if (!parseResult.success) {
        alert('参数解析失败，请重试')
        return
      }
      
      const { result } = parseResult
      if (!result) {
        alert('参数解析失败：返回结果为空')
        return
      }
      
      const { parameters, reasoning, confidence, requiresUserInput, userPrompt } = result
      
      console.log('🤖 AI智能解析结果:', {
        action,
        parameters,
        reasoning,
        confidence,
        requiresUserInput
      })
      
      // 如果AI建议需要用户输入，使用自定义日期时间弹窗而非浏览器prompt
      if (requiresUserInput && userPrompt) {
        if (action.includes('time') || action.includes('date')) {
          // 预置默认值：用任务现有截止时间或今天+2小时
          let preset = new Date()
          if (task.dueDate) {
            const d = new Date(task.dueDate)
            if (!isNaN(d.getTime())) preset = d
          } else {
            preset.setHours(preset.getHours() + 2, 0, 0, 0)
          }
          const yyyy = preset.getFullYear()
          const mm = String(preset.getMonth() + 1).padStart(2, '0')
          const dd = String(preset.getDate()).padStart(2, '0')
          const hh = String(preset.getHours()).padStart(2, '0')
          const mi = String(preset.getMinutes()).padStart(2, '0')
          setDateModalDate(`${yyyy}-${mm}-${dd}`)
          setDateModalTime(`${hh}:${mi}`)
          const iso = await new Promise<string | null>((resolve) => {
            dateModalResolverRef.current = resolve
            setDateModalOpen(true)
          })
          if (!iso) {
            console.log('用户取消了日期选择')
            return
          }
          parameters.dueDate = iso
        } else if (action.includes('priority')) {
          // 可扩展为优先级选择弹窗，此处暂不需要额外输入时直接继续
        }
      }
      
      // 执行任务更新
      if (task && Object.keys(parameters).length > 0) {
        const updateData: any = {}
        
        // 构建更新数据
        if (parameters.dueDate) updateData.dueDate = parameters.dueDate
        if (parameters.priority) updateData.priority = parameters.priority
        if (parameters.status) updateData.status = parameters.status
        if (parameters.category) updateData.category = parameters.category
        if (parameters.reminderMinutes) updateData.reminderMinutes = parameters.reminderMinutes
        if (parameters.notes) updateData.notes = parameters.notes
        
        // 特殊处理完成状态
        if (parameters.status === 'done') {
          await taskAPI.toggleTask(task.id)
        } else if (Object.keys(updateData).length > 0) {
          await taskAPI.updateTask(task.id, updateData)
        }
        
        // 显示成功消息
        const actionMessages = {
          'adjust_date': '任务时间已调整',
          'adjust_time': '任务时间已调整',
          'change_due_date': '任务截止日期已更新',
          'elevate_priority': '任务优先级已提升',
          'lower_priority': '任务优先级已降低',
          'mark_complete': '任务已标记为完成',
          'mark_in_progress': '任务已标记为进行中',
          'mark_preparing': '任务已标记为进行中',
          'set_reminder': '提醒已设置',
          'set_10min_reminder': '10分钟提醒已设置'
        }
        
        const message = actionMessages[action as keyof typeof actionMessages] || `动作"${action}"执行成功`
        showNotification({
          title: '操作成功',
          message: message,
          type: 'success',
          details: {
            aiExplanation: reasoning,
            confidence: confidence
          },
          duration: 3000
        })
        
        // 重新加载任务数据
        await loadTask()
      } else {
        // 对于不需要更新任务的动作，显示通用消息
        const generalMessages = {
          'accept': '建议已接受',
          'dismiss': '建议已忽略',
          'snooze': '稍后会再次提醒您',
          'merge_drink_reminders': '喝水提醒已合并',
          'end_work_today': '建议您结束今日工作，保持工作与生活的平衡！',
          'plan_tomorrow': '建议您规划明日日程，提前准备可以提高效率！',
          'breakdown_task': '任务分解功能正在开发中...',
          'optimize_schedule': '日程优化建议已应用',
          'balance_workload': '工作量平衡建议已应用'
        }
        
        const message = generalMessages[action as keyof typeof generalMessages] || `执行动作: ${action}`
        showNotification({
          title: '操作完成',
          message: message,
          type: 'success',
          duration: 3000
        })
      }
      
      // 记录动作执行
      await aiAPI.recordSuggestionFeedback(suggestion.id || 'task_detail_suggestion', action, 5, `用户执行了动作: ${action}`)
      
      // 从列表中移除建议
      setAiSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      
    } catch (error) {
      console.error('执行建议动作失败:', error)
      showNotification({
        title: '操作失败',
        message: '执行动作失败，请重试',
        type: 'error',
        duration: 4000
      })
    }
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      <NotificationComponent />
      {/* 顶部导航 - 现代化设计 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center justify-between px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">
            {isEditing ? '编辑任务' : '任务详情'}
          </h1>
          <div className="flex items-center gap-1">
            {isEditing ? (
              <>
                <button
                  onClick={handleCancelEdit}
                  className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
                >
                  <X size={20} />
                </button>
                <button
                  onClick={handleSaveEdit}
                  disabled={isSaving}
                  className="p-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Save size={20} />
                </button>
              </>
            ) : (
              <button
                onClick={handleEdit}
                className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
              >
                <Edit size={20} />
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="px-4 sm:px-6 pb-24 space-y-4">
        {/* 任务标题卡片 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <div className="flex items-start gap-4">
            <button
              onClick={handleToggleComplete}
              disabled={isEditing}
              className="flex-shrink-0 mt-1 hover:scale-110 transition-all disabled:opacity-50 touch-manipulation"
            >
              {task.completed ? (
                <CheckCircle size={24} className="text-green-500" />
              ) : (
                <Circle size={24} className="text-slate-400 hover:text-blue-500" />
              )}
            </button>
            <div className="flex-1 min-w-0">
              {isEditing ? (
                <div className="space-y-4">
                  <input
                    type="text"
                    value={editingTask?.title || ''}
                    onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, title: e.target.value }) : null)}
                    className="w-full text-xl font-semibold bg-transparent border-b-2 border-theme-border focus:border-blue-500 outline-none transition-colors pb-2"
                    placeholder="任务标题"
                  />
                  <textarea
                    value={editingTask?.description || ''}
                    onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, description: e.target.value }) : null)}
                    className="w-full bg-theme-bg-secondary border border-theme-border rounded-xl p-3 focus:border-blue-500 focus:bg-theme-bg outline-none transition-all resize-none text-sm"
                    placeholder="任务描述（可选）"
                    rows={3}
                  />
                </div>
              ) : (
                <>
                  <h2 className={`text-xl font-semibold leading-tight mb-2 ${
                    task.completed ? 'line-through text-theme-text-muted' : 'text-theme-text'
                  }`}>
                    {task.title}
                  </h2>
                  {task.description && (
                    <p className="text-theme-text-secondary text-sm leading-relaxed">{task.description}</p>
                  )}
                </>
              )}
            </div>
          </div>
        </div>

        {/* 任务详细信息卡片 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <h3 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
            <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
            任务详情
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {/* 创建时间 */}
            <div className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl">
              <Clock size={18} className="text-theme-text-muted flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-theme-text-muted mb-1">创建时间</div>
                {task.createdAt && (
                  <div className="space-y-1">
                    <div className="text-sm font-medium text-theme-text">
                      {TimeUtils.formatRelativeTime(task.createdAt)}
                    </div>
                    <div className="text-xs text-theme-text-secondary">
                      {TimeUtils.formatDate(new Date(task.createdAt), 'YYYY年MM月DD日 HH:mm')}
                    </div>
                    {/* 时间上下文信息 */}
                    <TimeLabel task={task} />
                  </div>
                )}
              </div>
            </div>
            
            {/* 截止日期和时间 */}
            <div className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl">
              <Calendar size={18} className="text-theme-text-muted flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-theme-text-muted mb-1">截止时间</div>
                {isEditing ? (
                  <div className="space-y-2">
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-theme-text-muted block mb-1">日期</label>
                        <input
                          type="date"
                          value={editingTask?.dueDate || ''}
                          onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, dueDate: e.target.value }) : null)}
                          className="text-sm font-medium bg-theme-bg border border-theme-border rounded-lg px-2 py-1 focus:border-blue-500 outline-none transition-colors w-full"
                        />
                      </div>
                      <div>
                        <label className="text-xs text-theme-text-muted block mb-1">时间</label>
                        <input
                          type="time"
                          value={editingTask?.dueTime || ''}
                          onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, dueTime: e.target.value }) : null)}
                          className="text-sm font-medium bg-theme-bg border border-theme-border rounded-lg px-2 py-1 focus:border-blue-500 outline-none transition-colors w-full"
                          placeholder="可选"
                        />
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-1">
                    <div className={`text-sm font-medium ${task.dueDate ? getDateStatus(task.dueDate) : 'text-theme-text-secondary'}`}>
                      {task.dueDate ? 
                        (task.dueTime ? 
                          `${task.dueDate} ${task.dueTime}` : 
                          task.dueDate
                        ) : 
                        '无截止日期'
                      }
                    </div>
                    {task.dueTime && (
                      <div className="text-xs text-blue-600 flex items-center gap-1">
                        ⏰ 具体时间: {task.dueTime}
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
            
            {/* 优先级 */}
            <div className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl">
              <Flag size={18} className="text-theme-text-muted flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-theme-text-muted mb-1">优先级</div>
                {isEditing ? (
                  <select
                    value={editingTask?.priority || 'P2'}
                    onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, priority: e.target.value }) : null)}
                    className="text-sm font-medium bg-theme-bg border border-theme-border rounded-lg px-2 py-1 focus:border-blue-500 outline-none transition-colors w-full"
                  >
                    <option value="P0">紧急</option>
                    <option value="P1">高</option>
                    <option value="P2">中</option>
                    <option value="P3">低</option>
                  </select>
                ) : (
                  <span className={`inline-flex items-center text-sm font-medium px-2 py-1 rounded-full ${getPriorityColor(task.priority)}`}>
                    {getPriorityLabel(task.priority)}
                  </span>
                )}
              </div>
            </div>
            
            {/* 分类 */}
            <div className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl">
              <Folder size={18} className="text-theme-text-muted flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-theme-text-muted mb-1">分类</div>
                {isEditing ? (
                  <select
                    value={editingTask?.category || 'work'}
                    onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, category: e.target.value }) : null)}
                    className="text-sm font-medium bg-theme-bg border border-theme-border rounded-lg px-2 py-1 focus:border-blue-500 outline-none transition-colors w-full"
                  >
                    <option value="work">💼 工作</option>
                    <option value="personal">👤 个人</option>
                    <option value="learning">📚 学习</option>
                    <option value="health">🏃 健康</option>
                    <option value="other">📝 其他</option>
                  </select>
                ) : (
                  <div className="text-sm font-medium text-theme-text flex items-center gap-2">
                    {(() => {
                      const IconComponent = getCategoryIcon(task.category)
                      return <IconComponent size={16} />
                    })()}
                    {getCategoryLabel(task.category)}
                  </div>
                )}
              </div>
            </div>
            
            {/* 标签 */}
            <div className="flex items-start gap-3 p-3 bg-theme-bg-secondary rounded-xl">
              <Tag size={18} className="text-theme-text-muted flex-shrink-0 mt-0.5" />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-theme-text-muted mb-1">标签</div>
                {isEditing ? (
                  <div>
                    <div className="flex flex-wrap gap-1.5 mb-2">
                      {editingTask?.tags?.map((tag: string, index: number) => (
                        <span
                          key={index}
                          className="px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs flex items-center gap-1"
                        >
                          {tag}
                          <button
                            onClick={() => setEditingTask(prev => prev ? ({
                              ...prev,
                              tags: prev.tags.filter((_: string, i: number) => i !== index)
                            }) : null)}
                            className="text-blue-500 hover:text-blue-700"
                          >
                            ×
                          </button>
                        </span>
                      ))}
                    </div>
                    <input
                      type="text"
                      placeholder="添加标签，按回车确认"
                      className="text-xs bg-theme-bg border border-theme-border rounded-lg px-2 py-1 focus:border-blue-500 outline-none transition-colors w-full"
                      onKeyPress={(e) => {
                        if (e.key === 'Enter' && e.currentTarget.value.trim()) {
                          const newTag = e.currentTarget.value.trim()
                          setEditingTask(prev => prev ? ({
                            ...prev,
                            tags: [...(prev.tags || []), newTag]
                          }) : null)
                          e.currentTarget.value = ''
                        }
                      }}
                    />
                  </div>
                ) : (
                  <div className="flex flex-wrap gap-1.5">
                    {task.tags && task.tags.length > 0 ? (
                      <TaskTag tags={task.tags} maxDisplay={10} showIcon={false} />
                    ) : (
                      <span className="text-sm text-theme-text-muted">无标签</span>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* 提醒设置 */}
            {task.dueDate && (
              <div className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl">
                <Calendar size={18} className="text-theme-text-muted flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="text-xs text-theme-text-muted mb-1">提醒设置</div>
                  {isEditing ? (
                    <div className="space-y-2">
                      <div className="text-xs text-theme-text-muted">提前多长时间提醒</div>
                      <div className="grid grid-cols-2 gap-1">
                        {[5, 15, 30, 60, 120, 1440].map((minutes) => (
                          <button
                            key={minutes}
                            onClick={() => setEditingTask(prev => prev ? ({ ...prev, reminderMinutes: minutes }) : null)}
                            className={`px-2 py-1 rounded text-xs font-medium transition-all ${
                              editingTask?.reminderMinutes === minutes
                                ? 'bg-blue-500 text-white'
                                : 'bg-theme-bg border border-theme-border text-theme-text hover:bg-blue-50'
                            }`}
                          >
                            {minutes < 60 ? `${minutes}分钟` : minutes === 60 ? '1小时' : minutes === 120 ? '2小时' : '1天'}
                          </button>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <div className="text-sm font-medium text-theme-text">
                      提前 {task.reminderMinutes && task.reminderMinutes < 60 ? `${task.reminderMinutes}分钟` : 
                            task.reminderMinutes === 60 ? '1小时' : 
                            task.reminderMinutes === 120 ? '2小时' : 
                            task.reminderMinutes === 1440 ? '1天' : 
                            '30分钟'} 提醒
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 备注 */}
        {(task.notes || isEditing) && (
          <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
            <h3 className="text-sm font-semibold text-theme-text mb-3 flex items-center gap-2">
              <div className="w-1 h-4 bg-amber-500 rounded-full"></div>
              备注
            </h3>
            {isEditing ? (
              <textarea
                value={editingTask?.notes || ''}
                onChange={(e) => setEditingTask(prev => prev ? ({ ...prev, notes: e.target.value }) : null)}
                className="w-full text-sm bg-theme-bg-secondary border border-theme-border rounded-xl p-3 focus:border-blue-500 focus:bg-theme-bg outline-none transition-all resize-none"
                placeholder="添加备注..."
                rows={3}
              />
            ) : (
              <p className="text-sm text-theme-text-secondary leading-relaxed bg-theme-bg-secondary rounded-xl p-3">
                {task.notes || '无备注'}
              </p>
            )}
          </div>
        )}

        {/* 子任务列表 */}
        {(task.subtasks && task.subtasks.length > 0 || !isEditing) && (
          <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
                <div className="w-1 h-4 bg-green-500 rounded-full"></div>
                子任务
                <span className="px-2 py-1 bg-theme-bg-tertiary text-theme-text-secondary text-xs rounded-full font-semibold">
                  {task.subtasks ? task.subtasks.filter((st: any) => st.completed).length : 0}/{task.subtasks ? task.subtasks.length : 0}
                </span>
              </h3>
              {!isEditing && (
                <button
                  onClick={() => setIsAddingSubtask(true)}
                  className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
                >
                  <Plus size={16} />
                </button>
              )}
            </div>
            
            <div className="space-y-3">
              {task.subtasks.map((subtask: any) => (
                <div key={subtask.id} className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl group hover:bg-theme-bg-tertiary transition-colors">
                  <button
                    onClick={() => handleSubtaskToggle(subtask.id)}
                    disabled={isEditing}
                    className="flex-shrink-0 hover:scale-110 transition-all disabled:opacity-50 touch-manipulation"
                  >
                    {subtask.completed ? (
                      <CheckCircle size={18} className="text-green-500" />
                    ) : (
                      <Circle size={18} className="text-slate-400 hover:text-blue-500" />
                    )}
                  </button>
                  
                  {editingSubtaskId === subtask.id ? (
                    <div className="flex-1">
                      <input
                        type="text"
                        value={editingSubtaskTitle}
                        onChange={(e) => setEditingSubtaskTitle(e.target.value)}
                        className="w-full text-sm bg-theme-bg border border-theme-border rounded-lg px-3 py-2 focus:border-blue-500 outline-none transition-colors"
                        onKeyPress={(e) => {
                          if (e.key === 'Enter') {
                            handleEditSubtask(subtask.id, editingSubtaskTitle)
                          }
                        }}
                        onBlur={() => handleEditSubtask(subtask.id, editingSubtaskTitle)}
                        autoFocus
                      />
                    </div>
                  ) : (
                    <>
                      <span 
                        className={`flex-1 text-sm cursor-pointer font-medium ${
                          subtask.completed ? 'line-through text-theme-text-muted' : 'text-theme-text'
                        }`}
                        onClick={() => {
                          if (!isEditing) {
                            setEditingSubtaskId(subtask.id)
                            setEditingSubtaskTitle(subtask.title)
                          }
                        }}
                      >
                        {subtask.title}
                      </span>
                      {!isEditing && (
                        <button
                          onClick={() => handleDeleteSubtask(subtask.id)}
                          className="opacity-0 group-hover:opacity-100 p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                        >
                          <Trash2 size={14} />
                        </button>
                      )}
                    </>
                  )}
                </div>
              ))}
              
              {/* 添加新子任务 */}
              {isAddingSubtask && (
                <div className="flex items-center gap-3 p-3 bg-blue-50 border-2 border-blue-200 border-dashed rounded-xl">
                  <Circle size={18} className="text-slate-400 flex-shrink-0" />
                  <input
                    type="text"
                    value={newSubtaskTitle}
                    onChange={(e) => setNewSubtaskTitle(e.target.value)}
                    placeholder="输入子任务标题..."
                    className="flex-1 text-sm bg-theme-bg border border-theme-border rounded-lg px-3 py-2 focus:border-blue-500 outline-none transition-colors"
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        handleAddSubtask()
                      } else if (e.key === 'Escape') {
                        setIsAddingSubtask(false)
                        setNewSubtaskTitle('')
                      }
                    }}
                    onBlur={() => {
                      if (newSubtaskTitle.trim()) {
                        handleAddSubtask()
                      } else {
                        setIsAddingSubtask(false)
                      }
                    }}
                    autoFocus
                  />
                </div>
              )}
            </div>
            
            {/* 子任务进度条 */}
            {task.subtasks && task.subtasks.length > 0 && (
              <div className="mt-5 pt-4 border-t border-theme-border">
                <div className="flex items-center justify-between text-xs text-theme-text-secondary mb-2">
                  <span className="font-medium">完成进度</span>
                  <span className="font-semibold">{task.subtasks && task.subtasks.length > 0 ? Math.round((task.subtasks.filter((st: any) => st.completed).length / task.subtasks.length) * 100) : 0}%</span>
                </div>
                <div className="w-full bg-slate-200 rounded-full h-2.5">
                  <div 
                    className="bg-gradient-to-r from-green-500 to-green-600 h-2.5 rounded-full transition-all duration-500 ease-out"
                    style={{ 
                      width: `${task.subtasks && task.subtasks.length > 0 ? (task.subtasks.filter((st: any) => st.completed).length / task.subtasks.length) * 100 : 0}%` 
                    }}
                  ></div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* AI智能建议区 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
              <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
              <Bot size={16} className="text-blue-600" />
              AI智能建议
            </h3>
            <button
              onClick={async () => {
                if (!showAISuggestions) {
                  setIsLoadingAI(true)
                  try {
                    const taskContextText = `任务上下文:\n- 标题: ${task.title}\n- 优先级: ${task.priority}\n- 分类: ${task.category}\n- 截止: ${task.dueDate || '无'}${task.dueTime ? ' ' + task.dueTime : ''}\n- 状态: ${task.completed ? '已完成' : '进行中'}\n- 是否重复: ${((task as any).isRecurring) ? '是' : '否'}`
                    const result = await aiAPI.getPersonalizedSuggestions(taskContextText, { mode: 'task', taskId: task.id })
                    if (result.success && result.suggestions) {
                      // 转换API返回的建议格式，确保包含taskId，并限制类型
                      const TASK_ALLOWED_TYPES = new Set(['priority_adjustment', 'auto_schedule', 'deadline_reminder', 'recurring_task_management', 'efficiency_tip', 'breakdown_task'])
                      const formattedSuggestions = result.suggestions
                        .filter((s: any) => TASK_ALLOWED_TYPES.has(s.type))
                        .map((suggestion: any) => ({
                          ...suggestion,
                          taskId: task.id,
                          id: suggestion.id || `task_detail_${Date.now()}_${Math.random()}`
                        }))
                      setAiSuggestions(formattedSuggestions)
                      setShowAISuggestions(true)
                    } else {
                      console.warn('获取AI建议失败:', result.error)
                    }
                  } catch (error) {
                    console.error('获取AI建议出错:', error)
                  } finally {
                    setIsLoadingAI(false)
                  }
                } else {
                  setShowAISuggestions(false)
                }
              }}
              disabled={isLoadingAI}
              className="px-3 py-2 bg-blue-600 text-white text-xs font-medium rounded-lg hover:bg-blue-700 transition-all disabled:opacity-50 shadow-sm"
            >
              {isLoadingAI ? '加载中...' : showAISuggestions ? '隐藏建议' : '获取建议'}
            </button>
          </div>
          
          {showAISuggestions && aiSuggestions.length > 0 && (
            <div className="space-y-3 mb-4">
              {aiSuggestions.map((suggestion, index) => (
                <div key={index} className="bg-theme-bg-secondary p-4 rounded-xl border border-theme-border">
                  <p className="text-sm text-theme-text mb-2 font-medium">{suggestion.message}</p>
                  {suggestion.reasoning && (
                    <p className="text-xs text-theme-text-secondary mb-3">{suggestion.reasoning}</p>
                  )}
                  {suggestion.actions && suggestion.actions.length > 0 && (
                    <div className="flex gap-2">
                      {suggestion.actions.map((action: any, actionIndex: number) => {
                        const key = `${suggestion.id || index}:${action.action}`
                        const isLoading = !!aiActionLoading[key]
                        const isAnyLoading = Object.values(aiActionLoading).some(Boolean)
                        return (
                          <button
                            key={actionIndex}
                            onClick={async () => {
                              if (isLoading || isAnyLoading) return
                              setAiActionLoading(prev => ({ ...prev, [key]: true }))
                              try {
                                await handleSuggestionAction(suggestion, action.action)
                              } finally {
                                setAiActionLoading(prev => ({ ...prev, [key]: false }))
                              }
                            }}
                            disabled={isLoading || isAnyLoading}
                            className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all flex items-center gap-2 ${
                              isLoading
                                ? 'bg-slate-200 text-slate-500 cursor-not-allowed'
                                : action.primary
                                ? 'bg-blue-600 text-white hover:bg-blue-700 shadow-sm disabled:bg-blue-400'
                                : 'bg-theme-bg text-theme-text-secondary border border-theme-border hover:bg-theme-bg-secondary disabled:opacity-60'
                            }`}
                            title={isLoading ? '处理中...' : action.label}
                          >
                            {isLoading ? (
                              <>
                                <Loader2 size={14} className="animate-spin" />
                                <span>处理中</span>
                              </>
                            ) : (
                              <span>{action.label}</span>
                            )}
                          </button>
                        )
                      })}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
          
          <div className="bg-theme-bg-secondary rounded-xl p-4">
            {task.completed ? (
              <p className="text-sm text-theme-text-secondary flex items-center gap-2">
                <span className="text-lg">🎉</span>
                任务已完成！您做得很好！
              </p>
            ) : isValidTaskDate(task.dueDate) && task.dueDate && new Date(task.dueDate) < new Date() ? (
              <div className="space-y-3">
                <p className="text-sm text-theme-text-secondary flex items-center gap-2">
                  <span className="text-lg">⚠️</span>
                  任务已过期，建议尽快完成或调整截止日期。
                </p>
                <div className="flex gap-2">
                  {(() => {
                    const anyLoading = Object.values(aiActionLoading).some(Boolean)
                    const adjustKey = 'overdue:adjust_date'
                    const remindKey = 'overdue:remind_later'
                    const isAdjustLoading = !!aiActionLoading[adjustKey]
                    const isRemindLoading = !!aiActionLoading[remindKey]
                    return (
                      <>
                        <button 
                          onClick={async () => {
                            if (isAdjustLoading || anyLoading) return
                            setAiActionLoading(prev => ({ ...prev, [adjustKey]: true }))
                            try {
                              await handleSuggestionAction({ id: 'overdue_task_suggestion' }, 'adjust_date')
                            } finally {
                              setAiActionLoading(prev => ({ ...prev, [adjustKey]: false }))
                            }
                          }}
                          disabled={isAdjustLoading || anyLoading}
                          className={`px-3 py-2 text-xs font-medium rounded-lg transition-all shadow-sm flex items-center gap-2 ${
                            isAdjustLoading
                              ? 'bg-blue-400 text-white cursor-not-allowed'
                              : 'bg-blue-600 text-white hover:bg-blue-700'
                          }`}
                          title={isAdjustLoading ? '处理中...' : '调整日期'}
                        >
                          {isAdjustLoading ? (
                            <>
                              <Loader2 size={14} className="animate-spin" />
                              <span>处理中</span>
                            </>
                          ) : (
                            <>
                              <Calendar size={14} />
                              <span className="hidden sm:inline">调整日期</span>
                            </>
                          )}
                        </button>
                        <button 
                          onClick={async () => {
                            if (isRemindLoading || anyLoading) return
                            setAiActionLoading(prev => ({ ...prev, [remindKey]: true }))
                            try {
                              await handleSuggestionAction({ id: 'overdue_task_suggestion' }, 'remind_later')
                            } finally {
                              setAiActionLoading(prev => ({ ...prev, [remindKey]: false }))
                            }
                          }}
                          disabled={isRemindLoading || anyLoading}
                          className={`px-3 py-2 text-xs font-medium rounded-lg transition-all flex items-center gap-2 ${
                            isRemindLoading
                              ? 'bg-theme-bg text-theme-text-secondary border border-theme-border cursor-not-allowed opacity-60'
                              : 'bg-theme-bg text-theme-text-secondary border border-theme-border hover:bg-theme-bg-secondary'
                          }`}
                          title={isRemindLoading ? '处理中...' : '稍后提醒'}
                        >
                          {isRemindLoading ? (
                            <>
                              <Loader2 size={14} className="animate-spin" />
                              <span>处理中</span>
                            </>
                          ) : (
                            <>
                              <Clock size={14} />
                              <span className="hidden sm:inline">稍后提醒</span>
                            </>
                          )}
                        </button>
                      </>
                    )
                  })()}
                </div>
              </div>
            ) : (
              <p className="text-sm text-theme-text-secondary flex items-center gap-2">
                <span className="text-lg">💡</span>
                根据您的任务情况，建议优先处理高优先级项目。
              </p>
            )}
          </div>
        </div>

        {/* 底部操作栏 */}
        <div className="fixed bottom-0 left-0 right-0 p-4 bg-theme-bg/95 backdrop-blur-sm border-t border-theme-border/60 shadow-lg">
          <div className="flex gap-3 max-w-md mx-auto">
            <button
              onClick={handleToggleComplete}
              className={`flex-1 py-3.5 rounded-xl font-semibold transition-all shadow-sm ${
                task.completed
                  ? 'bg-theme-bg-tertiary text-theme-text-secondary hover:bg-slate-200'
                  : 'bg-green-500 text-white hover:bg-green-600 shadow-green-500/25'
              }`}
            >
              {task.completed ? '标记未完成' : '标记完成'}
            </button>
            <button className="flex-1 py-3.5 bg-blue-500 text-white rounded-xl font-semibold hover:bg-blue-600 transition-all shadow-sm shadow-blue-500/25">
              计划时间
            </button>
          </div>
        </div>
      </div>
      {/* 日期时间选择弹窗 */}
      {dateModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40">
          <div className="bg-white rounded-2xl w-[90%] max-w-sm p-4 border border-slate-200 shadow-xl">
            <h4 className="text-sm font-semibold text-slate-900 mb-3">设置截止时间</h4>
            <div className="grid grid-cols-2 gap-3 mb-4">
              <div>
                <label className="text-xs text-slate-500 mb-1 block">日期</label>
                <input
                  type="date"
                  value={dateModalDate}
                  onChange={(e) => setDateModalDate(e.target.value)}
                  className="w-full px-2 py-2 rounded-lg border border-slate-200 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-slate-500 mb-1 block">时间</label>
                <input
                  type="time"
                  value={dateModalTime}
                  onChange={(e) => setDateModalTime(e.target.value)}
                  className="w-full px-2 py-2 rounded-lg border border-slate-200 text-sm"
                />
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => {
                  setDateModalOpen(false)
                  if (dateModalResolverRef.current) dateModalResolverRef.current(null)
                }}
                className="px-3 py-2 text-xs rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-50"
              >
                取消
              </button>
              <button
                onClick={() => {
                  if (!dateModalDate) {
                    alert('请选择日期')
                    return
                  }
                  const [h, m] = (dateModalTime || '10:00').split(':').map(Number)
                  const local = new Date(dateModalDate)
                  local.setHours(h || 10, m || 0, 0, 0)
                  const iso = local.toISOString()
                  setDateModalOpen(false)
                  if (dateModalResolverRef.current) dateModalResolverRef.current(iso)
                }}
                className="px-3 py-2 text-xs rounded-lg bg-blue-600 text-white hover:bg-blue-700"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
